 #include <sys/time.h>
 #include <signal.h>
 #include <stdio.h>
 #include <ucontext.h>

static ucontext_t ctx[3];

 void xthread_alarm_handler(int signo)
 {
    printf("switch\n");
    static int index = 0;
    int cur = index;
    int next = (cur + 1) % 3;
    index = next;
    swapcontext(&ctx[cur], &ctx[next]);
 }

static void func1(void)
{
    printf("func1 start\n");
    // 切换到func2
    // 返回后，切换到ctx[1].uc_link，也就是main的swapcontext返回处
    int i = 0;
    scanf("func1 %d", &i);
    printf("func1 end\n");
}
static void func2(void)
{
    printf("func2 start\n");
    // 返回后，切换到ctx[2].uc_link，也就是func1的swapcontext返回处
    int i = 0;
    scanf("func2 %d", &i);
    printf("func2 end\n");
}

int main (void)
{
    // 初始化context1，绑定函数func1和堆栈stack1
    char stack1[8192];

    getcontext(&ctx[0]);
    ctx[0].uc_stack.ss_sp   = stack1;
    ctx[0].uc_stack.ss_size = sizeof(stack1);
    ctx[0].uc_link = &ctx[0];
    printf("---1---\n");

    getcontext(&ctx[1]);
    ctx[1].uc_stack.ss_sp   = stack1;
    ctx[1].uc_stack.ss_size = sizeof(stack1);
    ctx[1].uc_link = &ctx[0];
    makecontext(&ctx[1], func1, 0);

    // 初始化context2，绑定函数func2和堆栈stack2
    char stack2[8192];
    getcontext(&ctx[2]);
    ctx[2].uc_stack.ss_sp   = stack2;
    ctx[2].uc_stack.ss_size = sizeof(stack1);
    ctx[2].uc_link = &ctx[0];
    makecontext(&ctx[2], func2, 0);

    struct itimerval value;
    value.it_value.tv_sec = 0;
    value.it_value.tv_usec = 1000;
    value.it_interval.tv_sec = 0;
    value.it_interval.tv_usec = 1000 * 200; // vulue is 10 ms
    if (setitimer(ITIMER_REAL, &value, NULL) < 0) {
        perror("xthread: install alarm failed!\n");
        return -1;
    }
    printf("---1--1---\n");
    signal(SIGALRM, xthread_alarm_handler);

    printf("---2---\n");
    int i = 0;
    scanf("input:%d", &i);
    printf("---3---\n");
    return 0;
}